package hust.rpc.client;


import hust.rpc.common.User;
import hust.rpc.procotol.JsonRpcResponse;
import hust.rpc.util.JsonUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.concurrent.Callable;

/**
 * 客户端业务处理 handler
 * 实现 rpc 调用
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    private static  final Logger logger = LogManager.getLogger();

    private volatile ChannelHandlerContext context;

    private final UnprocessedRequests unprocessedRequests;

    public NettyClientHandler() {
        unprocessedRequests = UnprocessedRequests.getUnprocessedRequests();
    }

    /**
     * 通道第一次被激活开始使用时，设置上下文参数
     * @param ctx
     * @throws Exception
     */

    /**
     * 读取返回的 rpc 调用结果
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        logger.info("channelRead 被调用");
        JsonRpcResponse response = JsonUtil.readResponseFromString((String) msg);

        unprocessedRequests.complete(response.getId(),response.getResult());
    }

    /**
     * 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.info("client catch exception ",cause);
        cause.printStackTrace();
        ctx.close();
    }



}
